package com.tre.jdevtemplateboot.common.redis.impl;

import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.common.redis.IRedisFileAuthorizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author JDev
 */
@Service
public class RedisFileAuthorizationServiceImpl implements IRedisFileAuthorizationService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private PropertiesConfig propertiesConfig;
    private String preFixUserId;

    @Override
    public List<String> getRedisAuthorization(String userId) {
        userId = RedisUserDeviceHeader.userDeviceHeader(userId);
        preFixUserId = getAuthorizationPreFixUserId(userId);
        Object object = redisTemplate.opsForValue().get(preFixUserId);
        if (object == null || "".equals(object)) {
            return Collections.emptyList();
        }
        return Arrays.asList(object.toString().split(","));
    }

    @Override
    public void setRedisAuthorization(String userId, String neededAuthorization) {
        userId = RedisUserDeviceHeader.userDeviceHeader(userId);
        preFixUserId = getAuthorizationPreFixUserId(userId);
        redisTemplate.opsForValue().set(preFixUserId, neededAuthorization, Long.parseLong(propertiesConfig.getTokenExpire()), TimeUnit.MILLISECONDS);
    }

    private String getAuthorizationPreFixUserId(String userId) {
        return propertiesConfig.getPreUserSubject() + "_file_authorize_" + userId;
    }
}
